
import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/util/customRoute.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:permission_handler/permission_handler.dart';

//toast的封装
class TostUtil {
  static show(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.grey[600],
        textColor: Colors.white,
        fontSize: 14.0
    );
  }
  //loading 遮罩
  static showLoading(BuildContext context, String text) {
    showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return new LoadingDialog(
        text: text,
      );
    });
  }
  //收起 遮罩
  static removeLoading(BuildContext context) {
    Navigator.of(context, rootNavigator: true).pop();
  }
}

//自定义的加载组件
class loadingWiget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: ThemeUtils.isDark(context) ? Colours.dark_bg_gray : Colors.white,
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: (MediaQuery.of(context).size.height - 3*MediaQuery.of(context).padding.top - 2*56)/2),
          ),
          SpinKitThreeBounce(
            color: Colors.blue,
            size: 20.0,
          )
        ],
      ),
    );
  }
} 


Widget buildHeader(BuildContext context,RefreshStatus mode){
  return Column(
    children: <Widget>[
      Container(
        padding: EdgeInsets.only(bottom: 10),
        child: CupertinoActivityIndicator(),
      ),
      Container(
        padding: EdgeInsets.only(bottom: 10),
        child: Center(
          child:Text(mode==RefreshStatus.idle?"下拉刷新":mode==RefreshStatus.refreshing?"刷新中...":
          mode==RefreshStatus.canRefresh?"释放更新":mode==RefreshStatus.completed?"刷新成功":"刷新失败")
        ),
      )
    ],
  );
}

Widget buildFooter(BuildContext context,LoadStatus mode){
  Widget body ;
  if(mode==LoadStatus.idle){
    body =  Text("上拉加载");
  }
  else if(mode==LoadStatus.loading){
    body =  Text("加载中...");
  }
  else if(mode == LoadStatus.failed){
    body = Text("加载失败！点击重试！");
  }
  else if(mode == LoadStatus.canLoading){
      body = Text("松手加载更多");
  }
  else{
    body = Text("没有更多数据了");
  }        
  return Column(
    children: <Widget>[
      Container(
        padding: EdgeInsets.only(top: 10, bottom: 10),
        child: CupertinoActivityIndicator(),
      ),
      Center(child:body)
    ],
  );
}

//自定义的 下拉刷新
class ZLRefreshHeader extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomHeader(
            builder: buildHeader,
            height: 80,
          );
  }
}

//自定义的 上拉加载
class ZLRefreshFooter extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomFooter(
            loadStyle: LoadStyle.ShowWhenLoading,
            builder: buildFooter,
          );
  }
}

//健康档案用的 textView
class ZLLTTextView extends StatefulWidget {
  ZLLTTextView({
    Key key,
    this.title: "",
    this.text: "",
  }): super(key: key);

  final String title;
  final text;
  
  @override
  _ZLLTTextViewState createState() => _ZLLTTextViewState();
}

class _ZLLTTextViewState extends State<ZLLTTextView> {
  bool isDark = false;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Container( 
        color: isDark ? Colours.dark_bg_gray : Colors.white,
        padding: EdgeInsets.only(top: 5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
              child: Text(widget.title,style: TextStyle(fontSize: 16, color: isDark ? Colours.dark_text : Colors.black),),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                reverse: true,
                child: Text(widget.text != null ? widget.text : "",style: TextStyle(fontSize: 14, color: isDark ? Colours.dark_text : Colours.text))
              ),
            )
          ],
        ),
      );
  }
}


// 自定义的图片选择 cell
class ZLImageSelectView extends StatefulWidget {
  ZLImageSelectView({
    Key key,
    this.title: "",
    this.images,
    this.isEdit = true,
    this.isBig = true,
    this.onChange
  }): super(key: key);

  final String title;
  List<String> images;
  final bool isEdit;
  final bool isBig;
  final Function onChange;
  @override
  _ZLImageSelectViewState createState() => _ZLImageSelectViewState();
}

class _ZLImageSelectViewState extends State<ZLImageSelectView> {
  bool isDark = false; 
  @override
  void initState() {
    super.initState();
  }

  //点击了图片添加按钮
  addImage(){
    //子组件给父组件传值 解决数据同步问题
    selectImages();
  }

  GalleryMode _galleryMode = GalleryMode.image;
  List<Media> _listImagePaths = List();

  Future<void> selectImages() async {
    try {
      _galleryMode = GalleryMode.image;
      List<Media> newList = await ImagePickers.pickerPaths(
          galleryMode: _galleryMode,
          selectCount: 9,
          showCamera: true,
          compressSize: 500,
          uiConfig: UIConfig(uiThemeColor: Colors.blue),
      );
      _listImagePaths.addAll(newList);
      widget.onChange(widget.images,_listImagePaths);
      setState(() {});
    } on PlatformException {}
  }

  //点击查看图片
  showImage(index) {
    List images = [];
    images.addAll(widget.images);
    for (var i = 0; i < _listImagePaths.length; i++) {
      images.add(_listImagePaths[i]);
    }
    // ImagePickers.previewImages(images,index);
    Navigator.of(context).push(CustomRoute(PhotoViewGalleryScreen(
        isEdit: widget.isEdit,
        images:images,//传入图片list
        index: index,//传入当前点击的图片的index
        heroTag: images[index].toString(),//传入当前点击的图片的hero tag （可选）
        onChange: (urlImages, fileImages) {
          widget.onChange(urlImages,fileImages);
          widget.images = urlImages;
          setState(() {
            _listImagePaths = fileImages;
          });
        },
    )));
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
     int column = widget.isBig ? 4 : 5;
     List<Widget> content = [];
     //先遍历前面的图片
     for (var i = 0; i < widget.images.length; i++) {
       content.add(
          Container(
          margin: EdgeInsets.fromLTRB(5, 5, 5, 5),
          width: (MediaQuery.of(context).size.width - 40 - 30) / column,
          height: (MediaQuery.of(context).size.width - 40 - 30) / column,
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              showImage(i);
            },
            child: CachedNetworkImage(
              imageUrl: widget.images[i],
              width: 100,
              height: 100,
              fit: BoxFit.fill,
            ),
          )
        ),
      );
     }

     //再遍历添加的图片
     for (var i = 0; i < _listImagePaths.length; i++) {
      content.add(
         Container(
          margin: EdgeInsets.fromLTRB(5, 5, 5, 5),
          width: (MediaQuery.of(context).size.width - 40 - 30) / column,
          height: (MediaQuery.of(context).size.width - 40 - 30) / column,
          child: GestureDetector(
            onTap: (){
              showImage(widget.images.length + i);
            },
            child: Image.file(
              File(_listImagePaths[i].path.toString()),
              fit: BoxFit.fill,
            )
          )
        )
      );
    }

    //添加一个添加图片
    if (widget.isEdit) {
      content.add(
          GestureDetector(
            onTap: addImage,
            child: Container(
              color: Colors.grey[200],
              margin: EdgeInsets.fromLTRB(5, 5, 5, 5),
              width: (MediaQuery.of(context).size.width - 40 - 30) / column,
              height: (MediaQuery.of(context).size.width - 40 - 30) / column,
              child: Icon(Icons.add_a_photo),
            ),
          )
      );
    }
    
    return Container(
      color: isDark ? Colours.dark_bg_gray : Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(widget.isBig ? 20 : 15, 10, 20, 0),
            child: Text(widget.title,style: TextStyle(fontSize: widget.isBig ? 18 : 16, color: isDark ? Colours.dark_text : Colours.text),),
          ),
          Container(
            color: isDark ? Colours.dark_bg_gray : Colors.white,
            padding: EdgeInsets.only(top: 15,left: 15,right: 15,bottom: 20),
            child: Wrap(
              children: content
            )
          )
        ],
      ),
    );
  }
}

// 自定义的 tags cell
class ZLTagsView extends StatefulWidget {
  const ZLTagsView({
    Key key,
    this.titles
  }): super(key: key);

  final List titles;

  @override
  _ZLTagsViewState createState() => _ZLTagsViewState();
}

class _ZLTagsViewState extends State<ZLTagsView> {
  bool isDark = false;
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    List<Widget> content = [];
     for (var i = 0; i < widget.titles.length; i++) {
      content.add(
         Container(
            padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
            margin: EdgeInsets.only(right: 8,top: 5),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.all(Radius.circular(10))
            ),
            child: Text(
              widget.titles[i],
              style: TextStyle(
                color: Colors.white,
                fontSize: 13
              )
            ),
        ),
      );
    }

    return Container(
      color: isDark ? Colours.dark_bg_gray : Colors.white,
      padding: EdgeInsets.only(left: 20,right: 20,bottom: 15,top: 5),
      child: Wrap(
        children: content,
      )
    );
  }
}

// 自定义的 选择 cell
class ZLSelectField extends StatefulWidget {
  const ZLSelectField({
    Key key,
    this.title: "",
    this.text: "",
    this.pliceHorder: "",
    this.onTap,
    this.isEdit: true,
    this.color,
  }): super(key: key);

  final String title;
  final text;
  final pliceHorder;
  final Function onTap;
  final bool isEdit;
  final Color color;

  @override
  _ZLSelectFieldState createState() => _ZLSelectFieldState();
}

class _ZLSelectFieldState extends State<ZLSelectField> {
  bool isDark = false;
  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).requestFocus(FocusNode());
        if (widget.isEdit) {
          widget.onTap();
        }
      }, 
      child: Container(
          height: 60,
          color: isDark ? Colours.dark_bg_gray : Colors.white,
          padding: EdgeInsets.only(left: 20,right: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
            Text(widget.title,style: TextStyle(fontSize: 18,color: isDark ? Colours.dark_text : Color(0xff333333)),),
            Expanded(
              child: Padding(padding: EdgeInsets.only(left: 15,right: 15),
                child: widget.text.toString().length > 0 ? Text(widget.text, style: TextStyle(fontSize: 16, color: widget.color != null ? widget.color: isDark ? Colours.dark_text : Colors.black)) : Text(widget.pliceHorder, style: TextStyle(fontSize: 14,color:Colors.grey))
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 自定义的 按钮
class ZLButton extends StatefulWidget {
  ZLButton({
    Key key,
    this.title : "",
    this.onTap,
    this.width : double.infinity,
    this.height : 45,
    this.fontSize : 16
  }): super(key: key);

  final String title;
  double width;
  double height;
  double fontSize;
  Function onTap;
  @override
  _ZLButtonState createState() => _ZLButtonState();
}

class _ZLButtonState extends State<ZLButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      margin: EdgeInsets.only(top: 10,left: 10,right: 10,bottom: 10),
      child: FlatButton(
          disabledColor: Colors.grey,
          onPressed: widget.onTap != null ? (){
            Future.delayed(Duration(milliseconds: 300), (){
              FocusScope.of(context).requestFocus(FocusNode());
            });
            widget.onTap();
          } : null,
          shape: StadiumBorder(side: BorderSide.none),
          color: Colors.blue,
          child: Text(
          widget.title,
          style: TextStyle(color: Colors.white,fontSize: widget.fontSize),
        ),
      ),
    );
  }
}

// 自定义的 textField
class ZLTextField extends StatefulWidget {
  ZLTextField({
    Key key,
    this.title = "",
    this.pliceHorder = "",
    this.controller,
    this.isEdit = true,
    this.inputType = TextInputType.text
  }): super(key: key);

  String title;
  String pliceHorder;
  TextEditingController controller = TextEditingController();
  bool isEdit;
  TextInputType inputType;
  
  @override
  _ZLTextFieldState createState() => _ZLTextFieldState();
}

class _ZLTextFieldState extends State<ZLTextField> { 
  bool isDark = false; 
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Container( 
        color: isDark ? Colours.dark_bg_gray : Colors.white,
        padding: EdgeInsets.only(left: 20,right: 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          textBaseline: TextBaseline.ideographic,
          children: <Widget>[
          Text(widget.title,style: TextStyle(fontSize: 18,color: isDark ? Colours.dark_text : Color(0xff333333)),),
          Expanded(
            child: Padding(padding: EdgeInsets.only(left: 15,right: 15,top: 15),
            child: TextFormField(
              keyboardType: widget.inputType,
              enabled: widget.isEdit,
              maxLines: 1,
              controller: widget.controller,
              textAlign: TextAlign.left,
              decoration: InputDecoration(
              hintText: (widget.pliceHorder),
              contentPadding: EdgeInsets.only(top: -30,bottom: 0),
                hintStyle: TextStyle(
                color: Color(0xff999999),
                fontSize: 14,
              ),
              alignLabelWithHint: true,
              border: OutlineInputBorder(borderSide: BorderSide.none),
              ),
              style: TextStyle(color: isDark ? Colours.dark_text : Colours.text),
            ),),
          ),
        ],
      ),
    );
  }
}

// 自定义的 textView
class ZLTextView extends StatefulWidget {
  ZLTextView({
    Key key,
    this.title = "",
    this.pliceHorder = "",
    this.controller,
    this.isEdit = true
  }): super(key: key);

  String title;
  String pliceHorder;
  TextEditingController controller = TextEditingController();
  bool isEdit;
  
  @override
  _ZLTextViewState createState() => _ZLTextViewState();
}

class _ZLTextViewState extends State<ZLTextView> {
  bool isDark = false;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Container( 
        color: isDark ? Colours.dark_bg_gray : Colors.white,
        padding: EdgeInsets.only(top: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Text(widget.title,style: TextStyle(fontSize: 18,color: isDark ? Colours.dark_text : Color(0xff333333)),),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                reverse: true,
                child: TextFormField(
                    style: TextStyle(color: isDark ? Colours.dark_text : Color(0xff333333)),
                    enabled: widget.isEdit,
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    controller: widget.controller,
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                    hintText: (widget.pliceHorder),
                    hintStyle: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 14,
                    ),
                    alignLabelWithHint: true,
                    border: OutlineInputBorder(borderSide: BorderSide.none),
                  ),
                ),
              ),
            )
          ],
        ),
      );
  }
}



class PhotoViewGalleryScreen extends StatefulWidget {
    List images=[];
    int index=0;
    String heroTag;
    PageController controller;
    Function onChange;
    bool isEdit;

    PhotoViewGalleryScreen({Key key,@required this.images,this.index,this.controller,this.heroTag,this.onChange,this.isEdit}) : super(key: key){
        controller=PageController(initialPage: index);
    }

    @override
    _PhotoViewGalleryScreenState createState() => _PhotoViewGalleryScreenState();
}

class _PhotoViewGalleryScreenState extends State<PhotoViewGalleryScreen> {
    int currentIndex=0;

    @override
    void initState() {
        // TODO: implement initState
        super.initState();
        currentIndex=widget.index;
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
          body: Stack(
            children: <Widget>[
              Positioned(
                  top: 0,
                  left: 0,
                  bottom: 0,
                  right: 0,
                  child: Container(
                      color: Colors.black,
                      child: PhotoViewGallery.builder(
                          scrollPhysics: const BouncingScrollPhysics(),
                          builder: (BuildContext context, int index) {
                              var image = widget.images[index];
                              if (image is String) {
                                return PhotoViewGalleryPageOptions(
                                  imageProvider: NetworkImage(image),
                                  heroAttributes: widget.heroTag.isNotEmpty?PhotoViewHeroAttributes(tag: widget.heroTag):null,  
                                );
                              }else{
                                return PhotoViewGalleryPageOptions(
                                  imageProvider: FileImage(File(image.path)),
                                  heroAttributes: widget.heroTag.isNotEmpty?PhotoViewHeroAttributes(tag: widget.heroTag):null,  
                                );
                              }
                              
                          },
                          itemCount: widget.images.length,
                          loadingChild: Container(
                            child: Center(
                              child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.white)),
                            ),
                          ),
                          pageController: widget.controller,
                          enableRotation: false,
                          onPageChanged: (index){
                            setState(() {
                                currentIndex=index;
                            });
                          },
                      )
                  ),
              ),
              Positioned(//图片index显示
                  top: MediaQuery.of(context).padding.top+15,
                  width: MediaQuery.of(context).size.width,
                  child: Center(
                      child: Text("${currentIndex+1}/${widget.images.length}",style: TextStyle(color: Colors.white,fontSize: 16)),
                  ),
              ),
              Positioned(//右上角删除按钮
                  right: 10,
                  top: MediaQuery.of(context).padding.top,
                  child: Offstage(
                    offstage: !widget.isEdit,
                    child: IconButton(
                        icon: Icon(Icons.delete,size: 20,color: Colors.white,),
                        onPressed: (){
                            //删除对应的数组
                            widget.images.removeAt(currentIndex);
                            List<String> urlImage = [];
                            List<Media> fileImage = [];
                            for (var i = 0; i < widget.images.length; i++) {
                              if (widget.images[i] is String) {
                                urlImage.add(widget.images[i]);
                              }else {
                                fileImage.add(widget.images[i]);
                              }
                            }
                            widget.onChange(urlImage,fileImage);
                            if (widget.images.length == 0) {
                              Navigator.of(context).pop();
                            }else{
                              setState(() {});
                            }
                            
                        },
                    ),
                  )
              ),
              Positioned(//右上角删除按钮
                  right: 10,
                  top: MediaQuery.of(context).padding.top,
                  child: Offstage(
                    offstage: widget.isEdit,
                    child: IconButton(
                        icon: Icon(Icons.save_alt,size: 20,color: Colors.white,),
                        onPressed: () async {

                          PermissionStatus permission =
                              await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
                          if (permission == PermissionStatus.granted) { 
                            //保存图片
                            var image = widget.images[currentIndex];
                            TostUtil.showLoading(context, "图片保存中");                
                            var response = await Dio().get(image, options: Options(responseType: ResponseType.bytes));
                            final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
                            TostUtil.removeLoading(context); 
                            if (result.toString() != '') {
                              TostUtil.show("保存成功");
                            }else {
                              TostUtil.show("保存失败");
                            }
                          } else {
                            PermissionHandler().requestPermissions(<PermissionGroup>[
                            PermissionGroup.storage, // 在这里添加需要的权限
                          ]);
                          }
                         
                        },
                    ),
                  )
              ),
              Positioned(//左上角返回按钮
                left: 10,
                top: MediaQuery.of(context).padding.top,
                child: IconButton(
                    icon: Icon(Icons.arrow_back_ios,size: 20,color: Colors.white,),
                    onPressed: (){
                        Navigator.of(context).pop();
                    },
                ),
              ),
            ],
          ),
      );
    }
}


class FadeRoute extends PageRouteBuilder {
    final Widget page;
    FadeRoute({this.page}): super(
        pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
        ) =>page,transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
        ) =>FadeTransition(
            opacity: animation,
            child: child,
        ),
    );
}

/*
 * 自定义等待加载提示框
 * Created by ZhangJun on 2018-11-29
 */

class LoadingDialog extends Dialog {
  final String text;

  LoadingDialog({Key key, @required this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Material(
      type: MaterialType.transparency,
      child: new Center(
        child: new SizedBox(
          width: 120.0,
          height: 120.0,
          child: new Container(
            decoration: ShapeDecoration(
              color: Color(0xffffffff),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                  Radius.circular(8.0),
                ),
              ),
            ),
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                new SpinKitThreeBounce(
                  color: Colors.blue,
                  size: 20.0,
                ),
                new Padding(
                  padding: const EdgeInsets.only(
                    top: 20.0,
                    left: 10.0,
                    right: 10.0
                  ),
                  child: Text(text)
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

